package com.shop.blockquenue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

class ShareDate{

    private BlockingQueue<String> queue  = null ;

    private int number = 0 ;

    private volatile boolean FLAG = true;

    public ShareDate(BlockingQueue<String> queue ){
        this.queue = queue;
    }

    public void prod(){
        while (FLAG){
            number ++;
            try {
                queue.offer(number+"" , 2, TimeUnit.SECONDS);
                System.out.println(Thread.currentThread().getName()+"Prod 生产了一个消息"+number);
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("prod is over ");
    }


    public void consumer() throws InterruptedException {
        while (FLAG){
            String poll = queue.poll(2, TimeUnit.SECONDS);
            System.out.println(Thread.currentThread().getName()+"消费了消息"+poll);

        }

        System.out.println("consumer is over");
    }

    public void stop(){
        this.FLAG = false;
    }
}
public class ProdConsumer {



    public static void main(String[] args) throws InterruptedException {
        ShareDate shareDate = new ShareDate(new ArrayBlockingQueue<>(3));
        new Thread(()->{
            shareDate.prod();
        }).start();

        new Thread(()->{
            try {
                shareDate.consumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        Thread.sleep(5*1000L);
        shareDate.stop();
        System.out.println("It's over!");
    }

}
